package net.zjitc.utils.dispacher;



import net.zjitc.utils.ControllerUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/8.
 */
//在此DispacherServlet里面去分配或调度到底是哪个类的方法
@WebServlet(name="DispacherServlet",urlPatterns = "/")
public class DispacherServlet extends HttpServlet {
      Map<String,Method> urlMap=new HashMap();
      Map<Method,Object> methodMap=new HashMap();

    @Override
    public void init() throws ServletException {
        //1,遍历net.zjitc.controller包下面的所有的.class文件，
        String packName="net.zjitc.controller";
        try {
            List<Class> classes= ControllerUtils.getAllClass(packName);
            //2.找到类对象的所有方法
            for (Class c:classes)
            {
                Method[] methods=c.getMethods();
                for(Method m:methods)
                {
                    //判断方法上面是否有注解，如果有注解，才把它们放在map集合中
                    URLMapping annotaion=m.getAnnotation(URLMapping.class);
                    if(annotaion!=null)
                    {
                        String url=annotaion.url();
                        urlMap.put(url,m);
                        Object o=c.newInstance();
                        methodMap.put(m,o);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**
         * 1.遍历net.controller包下面的所有的.class文件,
         * 2.找到类对象的所有的方法，
         * 3.判断方法上面是否有注解，如果有注解，才把它们放在map集合中，
         *
         */

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url=req.getServletPath();
        System.out.println(url);
        /**
         * net.zjitc.controller ------ .java
         *
         * urlMap<url,method>
         *     methodMap<method,object>
         *         method.invoke(object,request,response)
         */
        /*如果没有此servlet，则直接提示404错误*/
        if (!urlMap.containsKey(url)){
            resp.setStatus(404);
            return;
        }

        Method m=urlMap.get(url);
        Object o=methodMap.get(m);
        try {
            if(req.getMethod().equals("POST"))
            {
                req.setCharacterEncoding("utf-8");
            }
            String str=(String) m.invoke(o,req,resp);
            if(str==null)
            {
                return;
            }
            if(str!=null||(!"".equals(str)))
            {
                if(str.startsWith("Redirect:"))
                {
                    resp.sendRedirect(str.substring(9));
                }else {
                    req.getRequestDispatcher(str).forward(req,resp);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
